import React, { useEffect, useState } from "react";

function RevokeCountdown(props) {
    const [timeoutStr, setTimeoutStr] = useState("10s");
    const [countNum, setCountNum] = useState(props.count);

    useEffect(() => {
        if (props.enable) {
            setTimeoutStr("10s");
            setCountNum(10);
        }
    }, [props.enable]);

    useEffect(() => {
        if(countNum <= 0) {return;}
        const timer = setInterval(() => {
            if (countNum <= 1) {
                clearInterval(timer);
            }
            setCountNum((countNum) => countNum - 1);
            setTimeoutStr(`${countNum - 1}s`);
            if (countNum <= 1) {
                props.revokeCallback(true);
            }
        }, 1000);

        return () => {
            if (timer) {
                clearInterval(timer);
            }
        };
    }, [props.count, timeoutStr, countNum]);

    return <div> {countNum > 0 && `（${timeoutStr}）`}</div>;
}

export default React.memo(RevokeCountdown);
